using Newtonsoft.Json;
using RestSharp;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Screenshot
{
    [Flags]
    public enum KeyModifiers
    {
        None = 0,
        Alt = 1,
        Ctrl = 2,
        Shift = 4,
        WindowsKey = 8
    }
    public partial class MainForm : Form
    {
        private Point _mouseOffset;
        private ContextMenuStrip contextMenu;
        private ToolStripMenuItem exitItem;
        //OCRModelConfig config = null;
        //OCRResult ocrResult = new OCRResult();
        Image image;
        string identifyText = string.Empty;

        public static string AccessToken { get; private set; } = string.Empty;//百度文字识别token
        public MainForm()
        {
            InitializeComponent();
            Task.Run(() => GetAccessTokenAsync());
            MinimizePallets();
            this.DoubleBuffered = true;
            // config = null;
            // OCRParameter oCRParameter = new OCRParameter();
            // engine = new PaddleOCREngine(config, oCRParameter);
        }
        private async Task GetAccessTokenAsync()
        {
            var client = new RestClient("https://aip.baidubce.com/oauth/2.0/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", "");//应用的API Key；
            request.AddParameter("client_secret", "");//应用的Secret Key；
            var response = await client.ExecuteTaskAsync(request);
            var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
            AccessToken = result.access_token.ToString();
        }
        private void MinimizePallets()
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            this.Visible = false;
            this.KeyPreview = true;
            this.KeyDown += MainForm_KeyDown;
        }
        private async void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
                this.Visible = false;
                this.KeyPreview = true;
                pnl_translate.Visible = false;
                pnl_dentify.Visible = false;
                ClearMemory();
            }
            if (e.KeyCode == Keys.F2)
            {
                identifyText = await IdentifyingText();
            }

            if (e.KeyCode == Keys.F3)
            {
                if (!string.IsNullOrEmpty(identifyText))
                {
                    string feedbackResult = TranslateUtil.TranslatePost(identifyText.Trim(), Language.英语, Language.中文);
                    RootObject data = JsonConvert.DeserializeObject<RootObject>(feedbackResult);
                    rtb_translateText.Text = data.Trans_Result[0].Dst;
                    pnl_translate.Visible = true;
                    pnl_dentify.Width = imgWidth;
                    pnl_translate.Width = imgWidth;
                    this.ClientSize = new Size(imgWidth * 3, imgHeight);
                    //rtxtEnglish.AppendText($"1.要转化的语言From：{data.From}\r\n2.目标语言To：{data.To}\r\n3.转换之前的原文Src：{data.Trans_Result[0].Src}\r\n4.转换之后的结果Dst：{data.Trans_Result[0].Dst}");

                }
            }
            if (e.KeyCode == Keys.F4)
            {
                if (!string.IsNullOrEmpty(identifyText))
                {
                    string feedbackResult = TranslateUtil.TranslatePost(identifyText.Trim(), Language.中文, Language.英语);
                    RootObject data = JsonConvert.DeserializeObject<RootObject>(feedbackResult);
                    this.ClientSize = new Size(imgWidth * 3, imgHeight);

                    rtb_translateText.Text = data.Trans_Result[0].Dst;
                    pnl_translate.Visible = true;
                    pnl_translate.Width = imgWidth;
                    pnl_dentify.Width = imgWidth;
                    //rtxtEnglish.AppendText($"1.要转化的语言From：{data.From}\r\n2.目标语言To：{data.To}\r\n3.转换之前的原文Src：{data.Trans_Result[0].Src}\r\n4.转换之后的结果Dst：{data.Trans_Result[0].Dst}");

                }
            }
        }
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);

        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                //FrmMian为我窗体的类名
                MainForm.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                ScreenFrom.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                TranslateUtil.SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
        private void PerformTranslation(string sourceLanguage, string targetLanguage)
        {
            if (!string.IsNullOrEmpty(identifyText))
            {
                string feedbackResult = TranslateUtil.TranslatePost(identifyText.Trim(), sourceLanguage, targetLanguage);
                RootObject data = JsonConvert.DeserializeObject<RootObject>(feedbackResult);
                pnl_dentify.Visible = true;
                pnl_translate.Visible = true;
                pnl_dentify.Visible = true;
                imgWidth = pic_screenshot.Image.Width + 1;
                imgHeight = pic_screenshot.Image.Height + 1;
                this.ClientSize = new Size(imgWidth * 3, imgHeight);
                pnl_translate.Width = imgWidth;
                pnl_translate.Height = imgHeight;
                rtb_translateText.Text = data.Trans_Result[0].Dst;
            }
        }
        ScreenFrom screenFrom = null;
        int imgWidth;
        int imgHeight;
        private void button1_Click(object sender, EventArgs e)
        {


            using (Bitmap CatchBmp = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height))
            using (Graphics g = Graphics.FromImage(CatchBmp))
            {
                g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height));
                screenFrom = new ScreenFrom();
                screenFrom.BackgroundImage = CatchBmp;
                if (screenFrom.ShowDialog() == DialogResult.OK)
                {
                    IDataObject iData = Clipboard.GetDataObject();
                    image = (Image)iData.GetData(DataFormats.Bitmap);
                    string filePath = string.Empty;
                    if (image != null)
                    {
                        if (iData.GetDataPresent(DataFormats.Bitmap))
                        {
                            pic_screenshot.Image = image;
                            // 清楚剪贴板的图片
                            //Clipboard.Clear();
                        }
                    }
                }
            }
            this.TopMost = true;
            pnl_dentify.Visible = false;
            pnl_translate.Visible = false;
            imgWidth = pic_screenshot.Image.Width + 2;
            imgHeight = pic_screenshot.Image.Height + 2;
            this.ClientSize = new Size(imgWidth, imgHeight);
            pnl_screenshot.Width = imgWidth;
            pnl_screenshot.Height = imgHeight;
            Point originalLocation = screenFrom.DownPoint;
            this.Location = originalLocation;
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }
        public async Task<string> IdentifyingText()
        {
            if (image == null)
            {
                return string.Empty;
            }
            //ocrResult = engine.DetectText(image);// ocr识别文字
            string concatenatedWords = await ExtractTextFromImageAsync();
            if (concatenatedWords != null)
            {
                if (concatenatedWords.Length < 10)
                {
                    imgWidth = pic_screenshot.Image.Width + 10;
                    this.ClientSize = new Size(imgWidth * 2 + 10, imgHeight);
                }
                else
                {
                    imgWidth = pic_screenshot.Image.Width + 3;
                    this.ClientSize = new Size(imgWidth * 2 + 3, imgHeight);
                }
                pnl_dentify.Visible = true;
                pnl_translate.Visible = false;
                pnl_dentify.Visible = true;
                imgHeight = pic_screenshot.Image.Height;
                pnl_dentify.Width = imgWidth;
                pnl_dentify.Height = imgHeight;


                rtb_identifyText.Text = concatenatedWords;
                return concatenatedWords;
            }
            return string.Empty;
        }
        private async Task<string> ExtractTextFromImageAsync()
        {
            //https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token= 通用文字识别（标准版）
            //https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token= 通用文字识别（含位置信息版）
            //https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token= 通用文字识别（高精度版）
            //https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token= 通用文字识别（高精度含位置版）
            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + AccessToken);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Accept", "application/json");
            request.AddParameter("image", ImageToBase64(image));
            request.AddParameter("detect_direction", "false");
            request.AddParameter("detect_language", "false");
            request.AddParameter("paragraph", "false");
            request.AddParameter("probability", "false");

            var response = await client.ExecuteTaskAsync(request);
            var deserializedResponse = JsonConvert.DeserializeObject<Response>(response.Content);

            string concatenatedWords = string.Join(";", deserializedResponse.WordsResults.Select(item => item.Words)).TrimEnd(';');

            return concatenatedWords;
        }
        public static string ImageToBase64(Image image)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // 将图像保存到内存流中
                image.Save(ms, ImageFormat.Jpeg);
                // 将内存流的位置重置到开始
                ms.Position = 0;
                // 将内存流中的数据读取为字节数组
                byte[] imageBytes = new byte[ms.Length];
                ms.Read(imageBytes, 0, Convert.ToInt32(ms.Length));
                // 将字节数组转换为 Base64 字符串并返回
                return Convert.ToBase64String(imageBytes);
            }
        }
        private class Response
        {
            [JsonProperty("words_result")]
            public WordsResult[] WordsResults { get; set; }

            [JsonProperty("words_result_num")]
            public int WordsResultNum { get; set; }

            [JsonProperty("log_id")]
            public long LogId { get; set; }
        }

        private class WordsResult
        {
            [JsonProperty("words")]
            public string Words { get; set; }
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            uint ctrlHotKey = (uint)(KeyModifiers.Alt | KeyModifiers.Ctrl);
            HotKey.RegisterHotKey(Handle, 100, ctrlHotKey, Keys.A);
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("确认要关闭截图系统吗？", "确认", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                HotKey.UnregisterHotKey(Handle, 100);
            }
        }
        private void GlobalKeyProcess()
        {
            this.WindowState = FormWindowState.Minimized;
            Thread.Sleep(200);
            button1_Click(null, null);
        }
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    if (m.WParam.ToString() == "100")
                    {
                        GlobalKeyProcess();
                    }

                    break;
            }
            base.WndProc(ref m);
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void MainForm_Resize(object sender, EventArgs e)
        {
            // 判断只有最小化时，隐藏窗体
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }
        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip.Show();
            }
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
            }
        }
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            _mouseOffset = new Point(-e.X, -e.Y);

        }
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(_mouseOffset);
                Location = mousePos;
            }
        }
    }
}
